package com.zxl.placeholderParse;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;

/**
 * 邮件模版解析
 * @author zxl
 *
 */
public class MailTemplateConfig {
    
    public static void test1() throws IOException {
        String regex = "\\$\\{([\\p{Blank}\\w]+)\\}";
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = null;
        Map<String, String> map = new HashMap<String, String>();
        map.put("tradeNo", "B201606070000008");
        map.put("bookNo", "ADWWEG");
        map.put("payTotal", "270.0");
        InputStream is = MailTemplateConfig.class.getClassLoader().getResourceAsStream("paysuccess2.html");
        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        String str = null;
        StringBuffer buffer = new StringBuffer();
        while ((str = reader.readLine()) != null) {
            matcher = pattern.matcher(str);
            while (matcher.find()) {
                str = str.replace(matcher.group(0), map.get(matcher.group(1).trim()));
            };
            buffer.append(str);
        }
        reader.close();
        System.out.println(buffer.toString());
    }
    
    public static void test2() throws IOException {
        String regex = "\\$\\{([\\p{Blank}\\w]+)\\}";
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = null;
        Map<String, String> map = new HashMap<String, String>();
        map.put("tradeNo", "B201606070000008");
        map.put("bookNo", "ADWWEG");
        map.put("payTotal", "270.0");
        InputStream is = MailTemplateConfig.class.getClassLoader().getResourceAsStream("paysuccess2.html");
        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        String str = null;
        StringBuffer buffer = new StringBuffer();
        while ((str = reader.readLine()) != null) {
            matcher = pattern.matcher(str);
            while (matcher.find()) {
                str = str.replace(matcher.group(0), map.get(matcher.group(1)).trim());
            };
            buffer.append(str);
        }
        reader.close();
        System.out.println(buffer.toString());
    }
    
    public static void test3() throws IOException, NoSuchMethodException, SecurityException {
        String regex = "\\$\\{([\\p{Blank}\\w]+)\\}";
        String forReg = "<(\\/)?foreach";
        boolean nodeFlag = false;
        Pattern elPar = Pattern.compile(regex);
        Pattern forPar = Pattern.compile(forReg);
        Matcher matcher = null;
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("tradeNo", "B201606070000008");
        map.put("bookNo", "ADWWEG");
        map.put("payTotal", "270.0");
        List<TestDomain> testList = new ArrayList<TestDomain>();
        TestDomain td = new TestDomain("abc",15,"男");
        testList.add(td);
        map.put("testList", testList);
        InputStream is = MailTemplateConfig.class.getClassLoader().getResourceAsStream("paysuccess2.html");
        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        String str = null;
        StringBuffer buffer = new StringBuffer();
        List<String> list = new ArrayList<String>();
        while ((str = reader.readLine()) != null) {
            matcher = forPar.matcher(str);
            while (matcher.find()) {
                nodeFlag = true;
                if (matcher.group(1) != null && matcher.group(1).equals("/")) {
                    //TODO 处理循环
                    doForLoop(list,map,buffer);
                    nodeFlag = false;
                }
            }
            if (nodeFlag) { //for循环范围内的语句直接加入list
                list.add(str.trim());
            }else { //for循环外的需要做此判断
                matcher = elPar.matcher(str);
                while (matcher.find()) {
                    str = str.replace(matcher.group(0), String.valueOf(map.get(matcher.group(1).trim())));
                };
            }
            buffer.append(str);
        }
        reader.close();
//        System.out.println(list.toString());
//        System.out.println(buffer.toString());
    }
    
    /**
     * 将for标签执行for循环
     * @param list  for循环体
     * @param map    将用来进行替换值的集合
     * @param sb    处理之后拼接的html
     * @throws SecurityException 
     * @throws NoSuchMethodException 
     */
    @SuppressWarnings("unchecked")
	public static void doForLoop(List<String> list,Map<String, Object> map, StringBuffer sb) throws NoSuchMethodException, SecurityException{
        //for循环的头部
        String forHead = list.remove(0);
        String regex = "([a-zA-Z]+)\\=\"(\\p{Blank}*[\\w]+\\p{Blank}*)\"";
        Pattern elPar = Pattern.compile(regex);
        Matcher matcher = elPar.matcher(forHead);
        List<Object> lo = new ArrayList<Object>();
        String attrName = null;
        String attrValue = null;
        while (matcher.find()) {
            forHead = forHead.replace(matcher.group(0), String.valueOf(map.get(matcher.group(2).trim())));
            attrName = matcher.group(1).trim();
            if (attrName.equals("collection")) {
                attrValue = matcher.group(2).trim();
                lo = (List<Object>) map.get(attrValue);
                lo = lo == null ? new ArrayList<Object>() : lo;
            }
        };
        System.out.println(forHead);
        for (Object obj : lo) {
            for (int i = 0; i < list.size(); i++) {
                System.out.println(list.get(i));
                matcher = elPar.matcher(list.get(i));
                while (matcher.find()) {
//                    forHead = forHead.replace(matcher.group(0), String.valueOf(map.get(matcher.group(1).trim())));
                    Method method = obj.getClass().getMethod("get" + String.valueOf(matcher.group(1).trim()));
                    try {
                        System.err.println(method.invoke(obj));
                    } catch (IllegalAccessException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    } catch (IllegalArgumentException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    } catch (InvocationTargetException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                };
            }
        }
    }
    
    public static void jsoupTest() throws IOException {
        String str = "<foreach collection=\"list\" var=\"asd\">";
        Document doc = Jsoup.parse(str);
//        InputStream is = MailTemplateConfig.class.getClassLoader().getResourceAsStream("paysuccess2.html");
//        Document doc = Jsoup.parse(is, "UTF-8", "");
//        Iterator<Element> lt = doc.getAllElements().iterator();
//        while(lt.hasNext()){
//            System.out.println(doc);
//        }
//        System.out.println(doc.getAllElements().text());
    }
    
    public static void main(String[] args) throws IOException, NoSuchMethodException, SecurityException {
//        test1();
//        test2();
        test3();
//        jsoupTest();
    }
}
